package com.yy.show.util;

import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import com.yy.base.util.DateTime;
import com.yy.base.util.StringUtil;
import com.yy.module.entity.ModuleField;
import com.yy.module.entity.ModuleInfo;
import com.yy.module.entity.ModuleQueryField;

/**
 * 查询模块处理类
 */
@SuppressWarnings("unchecked")
public class ModuleQueryHandle extends ModuleHandle {
	public ModuleQueryHandle(ModuleInfo module, HttpServletRequest request) {
		super(module, request);
	}
	/**
	 * 获取查询SQL
	 */
	public String getQuerySql() {
		return sql.toString();
	}
	
	/**
	 * 判断参数格式是否正确
	 */
	public boolean hasError() {
		sql = new StringBuilder();
		sql.append("select ");
		List<ModuleField> list = module.getFieldList();
		if (list.isEmpty()) {
			error = "当前显示列表不能为空！";
			return true;
		}
		ModuleField field = null;
		tables = new HashMap<String, String>();
		String t = null;
		StringBuilder orderBy = new StringBuilder();
		
		for (int i = 0, size = list.size(); i < size; i++) {
			field = list.get(i);
			t = tables.get(field.getTableName());
			if (t == null) {
				t = "t" + i;
				tables.put(field.getTableName(), t);
			}
			if (i != 0) {
				sql.append(",");
			}
			sql.append(t).append(".").append(field.getFieldName()).append(" ").append(getAliasName(field.getTableName() + "_" + field.getFieldName()));
			
			//判断是否排序字段
			if (StringUtil.isNotEmpty(field.getOrderByDesc())) {
				if (orderBy.length() > 0) {
					orderBy.append(",");
				}
				orderBy.append(t).append(".").append(field.getFieldName()).append(" ").append(field.getOrderByDesc());
			}
		}
		
		sql.append(" from ");
		int i = 0;
		for (String table : tables.keySet()) {
			if (i > 0) {
				sql.append(",");
			}
			sql.append(table).append(" ").append(tables.get(table));
			i ++;
		}
		sql.append(" where 1=1 ");
		//判断是否有多表关联
		if (tables.keySet().size() > 1) {
			
		}
		//查询条件
		values = new HashMap();
		List<ModuleQueryField> queryList = module.getQueryFieldList();
		Object value = null;
		DateTime dt = null;
		String format = null;
		ModuleQueryField query = null;
		
		for (int index = 0; index < queryList.size(); index++) {
			query = queryList.get(index);
			
			//如果是隐藏的，并且有默认值，处理默认值
			if (query.getIsHide() == 1 && StringUtil.isNotEmpty(query.getDefaultValue())) {
				value = getDefaultValue(query.getDefaultValue());
				if (StringUtil.isEmpty(value)) {
					if (query.getIsNotNull() == 1) {
						error = "[" + query.getName() + "] 不能为空！";
						return true;
					}
				}
			} else {
				value = request.getParameter(query.getTableName() + "_" + query.getFieldName());
				if (value == null) {
					value = request.getParameter(query.getFieldName());
				}
				if (StringUtil.isEmpty(value)) {
					if (query.getIsNotNull() == 1) {
						error = "[" + query.getName() + "] 不能为空！";
						return true;
					}
					continue;
				}
			}
			if (StringUtil.isEmpty(value)) {
				sql.append(" and ").append(tables.get(query.getTableName())).append(".").append(query.getFieldName()).append(" is null");
			} else if (ModuleField.DATA_VALUE_DATE.equals(query.getType())) {
				if (value instanceof String) {
					format = query.getFormat() != null && query.getFormat().length() > 7 ? query.getFormat() : "yyyy-MM-dd";
					try {
						value = new SimpleDateFormat(format).parse((String)value);
					} catch (Exception e) {
						error = "[" + query.getName() + "] 解析成时间格式 \"" + format + "\" 错误！";
						return true;
					}
					sql.append(" and (").append(tables.get(query.getTableName())).append(".").append(query.getFieldName()).append(" >= :p").append(index);
					values.put("p" + index, value);
				}
				if (query.getIsRange() != null && query.getIsRange() == 1) {
					try {
						value = request.getParameter(query.getTableName() + "_" + query.getFieldName() + "_END_");
						if (value != null && !"".equals(value)) {
							dt = new DateTime((String)value, format);
							dt.addDay(1);
							sql.append(" and ").append(tables.get(query.getTableName())).append(".").append(query.getFieldName()).append(" < :pp").append(index);
							values.put("pp" + index, dt.getDate());
						}
					} catch (Exception e) {
						error = "[" + query.getName() + "] 解析成时间格式 \"" + format + "\" 错误！";
						return true;
					}
				}
				sql.append(")");
			} else if (ModuleField.DATA_VALUE_NUMBER.equals(query.getType())) {
				sql.append(" and (").append(tables.get(query.getTableName())).append(".").append(query.getFieldName()).append(" >= :p").append(index);
				values.put("p" + index, value);
				if (query.getIsRange() != null && query.getIsRange() == 1) {
					value = request.getParameter(query.getTableName() + "_" + query.getFieldName() + "_END_");
					if (value != null && !"".equals(value)) {
						sql.append(" and ").append(tables.get(query.getTableName())).append(".").append(query.getFieldName()).append(" <= :pp").append(index);
						values.put("pp" + index, value);
					}
				}
				sql.append(")");
			} else {
				if (ModuleField.DATA_VALUE_TEXT.equals(query.getType())) {
					sql.append(" and ").append(tables.get(query.getTableName())).append(".").append(query.getFieldName()).append(" like :p").append(index);
					values.put("p" + index, "%" + value.toString() + "%");
				} else {
					sql.append(" and ").append(tables.get(query.getTableName())).append(".").append(query.getFieldName()).append(" = :p").append(index);
					values.put("p" + index, value.toString());
				}
			}
		}
		if (orderBy.length() > 0) {
			sql.append(" order by ").append(orderBy);
		}
		return false;
	}
	/**
	 * 获取唯一数据
	 */
	public boolean hasError(String type) {
		sql = new StringBuilder();
		sql.append("select ");
		List<ModuleField> list = module.getFieldList();
		tables = new HashMap<String, String>();
		values = new HashMap();
		ModuleField field = null;
		String t = null;
		Object value = null;
		String format = null;
		
		for (int i = 0, size = list.size(); i < size; i++) {
			field = list.get(i);
			t = tables.get(field.getTableName());
			if (t == null) {
				t = "t" + i;
				tables.put(field.getTableName(), t);
			}
			if (i != 0) {
				sql.append(",");
			}
			sql.append(t).append(".").append(field.getFieldName()).append(" ").append(getAliasName(field.getTableName() + "_" + field.getFieldName()));
		}
		sql.append(" from ");
		int i = 0;
		for (String table : tables.keySet()) {
			if (i > 0) {
				sql.append(",");
			}
			sql.append(table).append(" ").append(tables.get(table));
			i ++;
		}
		sql.append(" where 1=1 ");
		
		//判断是否有多表关联
		if (tables.keySet().size() > 1) {
			
		}
		//处理必须查询条件
		List<ModuleQueryField> queryList = module.getQueryFieldList();
		ModuleQueryField query = null;
		
		for (int index = 0; index < queryList.size(); index++) {
			query = queryList.get(index);
			//如果是隐藏的，并且有默认值，处理默认值
			if (query.getIsHide() == 1 && StringUtil.isNotEmpty(query.getDefaultValue())) {
				value = getDefaultValue(query.getDefaultValue());
				if (StringUtil.isEmpty(value)) {
					if (query.getIsNotNull() == 1) {
						error = "[" + query.getName() + "] 不能为空！";
						return true;
					}
				}
			} else {
				value = request.getParameter(query.getTableName() + "_" + query.getFieldName());
				if (value == null) {
					value = request.getParameter(query.getFieldName());
				}
				if (StringUtil.isEmpty(value)) {
					if (query.getIsNotNull() == 1) {
						error = "[" + query.getName() + "] 不能为空！";
						return true;
					}
				}
			}
			if (StringUtil.isEmpty(value)) {
				sql.append(" and ").append(tables.get(query.getTableName())).append(".").append(query.getFieldName()).append(" is null");
			} else if (ModuleField.DATA_VALUE_DATE.equals(query.getType())) {
				format = query.getFormat() != null && query.getFormat().length() > 7 ? query.getFormat() : "yyyy-MM-dd";
				try {
					value = new SimpleDateFormat(format).parse((String)value);
				} catch (Exception e) {
					error = query.getName() + "解析成时间格式 \"" + format + "\" 错误！";
					return true;
				}
				sql.append(" and ").append(tables.get(query.getTableName())).append(".").append(query.getFieldName()).append(" = :p").append(index);
				values.put("p" + index, value);
			} else if (ModuleField.DATA_VALUE_NUMBER.equals(query.getType())) {
				sql.append(" and ").append(tables.get(query.getTableName())).append(".").append(query.getFieldName()).append(" = :p").append(index);
				values.put("p" + index, value);
			} else {
				if (ModuleField.DATA_VALUE_TEXT.equals(query.getType())) {
					sql.append(" and ").append(tables.get(query.getTableName())).append(".").append(query.getFieldName()).append(" like :p").append(index);
					values.put("p" + index, "%" + value.toString() + "%");
				} else {
					sql.append(" and ").append(tables.get(query.getTableName())).append(".").append(query.getFieldName()).append(" = :p").append(index);
					values.put("p" + index, value.toString());
				}
			}
		}
		return false;
	}
	
	private String getAliasName(String name) {
		if (name.length() > 30) {
			name = name.substring(name.length() - 30);
			if (name.startsWith("_")) {
				name = name.substring(1);
			}
		}
		return name;
	}
}